package cur.tool.common.filter;

import cur.nature.framework.core.log.LOG;
import cur.nature.framework.core.thread.MyThreadLocal;
import cur.nature.framework.core.util.StringUtil;
import cur.tool.common.AppContextUtil;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import java.io.IOException;
import java.util.Optional;

/**
 *
 * @author wujian
 * @date 2017-07-03
 *
 */
//@ConditionalOnProperty( value = {"com.cur.cloud.authorizeFilter"},matchIfMissing = false)
@Order(-1)
@WebFilter(urlPatterns = "/*", filterName = "AuthorizeFilter")
public class AuthorizeFilter implements Filter {
	@Value("${cur.core.server.config.mvc.swagger:false}")
	private Boolean swaggerOn;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		Long spentTime = 0L;
		final HttpServletRequest servletRequest = ((HttpServletRequest) request);
		String uri = servletRequest.getRequestURI();
		boolean isIgnore = AppContextUtil.isIgnoreURLWithLog(uri);
		try {
			//处理跨域
			if("OPTIONS".equals(servletRequest.getMethod())){
				LOG.info("OPTIONS is : " );
				filterChain.doFilter(request,response);
				return;
			}
			// 处理ico
			if (servletRequest.getRequestURI().equals("/favicon.ico")) {
				return;
			}
			long start = System.currentTimeMillis();
//		String id = DateUtil.parseDateToStr(new Date(),DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS);
//		String id = IdUtil.fastUUID();
			// 优先读取请求头里的 trace_id, 用于形成调用链
			final String traceId = ((HttpServletRequest) request).getHeader(MyThreadLocal.TRACE_ID);
			final String userId = ((HttpServletRequest) request).getHeader(MyThreadLocal.USER_ID);
			final String id = StringUtil.isBlank(traceId) ? System.currentTimeMillis()+"" : traceId;
//			final String id = System.currentTimeMillis()+"";
			MyThreadLocal.getCurrentThread().put(MyThreadLocal.TRACE_ID,id);
			MyThreadLocal.getCurrentThread().put(MyThreadLocal.USER_ID, Optional.ofNullable(userId).equals(""));

			LOG.info("请求开始: "+ uri + " , 用户: "+userId+" ------", !isIgnore);
			LOG.debug("sessionId: "+ servletRequest.getSession().getId());

			filterChain.doFilter(request,response);
			//耗时
			spentTime = System.currentTimeMillis()-start;

			// 保存日志
			if (uri.endsWith("/operate")) {
				final String userId2 = "1";
				final String param = (String) MyThreadLocal.getCurrentThread().get(MyThreadLocal.TRACE_ID);
			}

		}catch (Exception ex) {
			LOG.error("filter err:",ex);
			throw ex;
		} finally {
			//打印结果
			LOG.info("请求结束: "+ uri + " , 耗时: " + (spentTime/1000f) +" 秒 ------", !isIgnore);
//			LOG.info("总耗时 : "+(spentTime/1000f)+" 秒************************************************************");
			MyThreadLocal.getCurrentThread().removeAll();
		}


	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException { }

	@Override
	public void destroy() { }
}
